package com.zmj.sy.mom.srv.aps.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.google.common.collect.Lists;
import com.zmj.sy.mom.srv.aps.bean.entity.base.PoolLog;
import com.zmj.sy.mom.srv.aps.bean.entity.base.PoolPart;
import com.zmj.sy.mom.srv.aps.bean.entity.mes.*;
import com.zmj.sy.mom.srv.aps.bean.entity.order.*;
import com.zmj.sy.mom.srv.aps.bean.entity.reportErp.NoreportErpConfig;
import com.zmj.sy.mom.srv.aps.bean.entity.third.SinoCamReceiveNestPart;
import com.zmj.sy.mom.srv.aps.bean.vo.workshop.WorkshopPartInReqVo;
import com.zmj.sy.mom.srv.aps.feign.WmsApiClient;
import com.zmj.sy.mom.srv.aps.mapper.*;
import com.zmj.sy.mom.srv.aps.service.PartService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.zmj.sy.mom.srv.aps.utils.WorkshopProp.WL_PHASE_CODE;

@Slf4j
@RequiredArgsConstructor
@Service
public class PartUtilService {
    private final ApsWorkDetailMapper apsWorkDetailMapper;
    private final WorkDetailTaskMapper workDetailTaskMapper;
    private final NoreportErpConfigMapper noreportErpConfigMapper;
    private final PartPalletMapper partPalletMapper;
    private final PartLogMapper partLogMapper;
    private final PartMapper partMapper;
    private final WmsApiClient wmsApiClient;
    private final WorkRecordMapper workRecordMapper;
    private final  PartService  partService;
    private final ApsWorkOrderMapper apsWorkOrderMapper;
    private final ApsOrderMapper apsOrderMapper;

    private final OrderMapper orderMapper;
    private final OrderBomMapper orderBomMapper;
    private final PoolPartMapper poolPartMapper;
    private final PoolLogMapper poolLogMapper;

    public Optional<ApsWorkDetail> getNextWorkDetail(ApsWorkDetail apsWorkDetail) {
        List<ApsWorkDetail> allDetail = apsWorkDetailMapper.lambdaQuery().eq(ApsWorkDetail::getMaterNo, apsWorkDetail.getMaterNo()).eq(ApsWorkDetail::getApsWorkOrderId, apsWorkDetail.getApsWorkOrderId()).list();
        Optional<ApsWorkDetail> min = allDetail.stream().filter(e -> e.getPhaseSeq() > apsWorkDetail.getPhaseSeq()).min(Comparator.comparing(ApsWorkDetail::getPhaseSeq));
        return min;
    }

    /**
     * 分拣创建工单任务
     *
     * @param nextAwd
     * @param prePhaseCode
     * @param nestPart
     */
    public void makeWorkDetailTask(WorkDetailTask oldTask,ApsWorkDetail nextAwd, int successQuantity, String prePhaseCode, SinoCamReceiveNestPart nestPart) {

        if (nextAwd.getStatus() < 2) {
            nextAwd.setStatus(2);
        }
        apsWorkDetailMapper.updateById(nextAwd);
        if (successQuantity> 0) {
        /*      List<WorkDetailTask> taskList = workDetailTaskMapper.lambdaQuery()
                    .eq(WorkDetailTask::getMaterCode, nextAwd.getMaterNo())
                    .eq(WorkDetailTask::getApsWorkDetailId, nextAwd.getId())
                    .list();
            //  允许进行超计划报工
         int reduce = taskList.stream().mapToInt(WorkDetailTask::getTotalCount).sum();
           if(reduce + successQuantity > nextAwd.getTotalCount().intValue()){
               Assert.isTrue(WorkshopProp.FJ_PHASE_CODE.equals(oldTask.getPhaseCode()), "报工数量已超过计划总数量并且不是分拣报工,超出数量="+ (reduce + successQuantity -nextAwd.getTotalCount().intValue()));
           }*/
            WorkDetailTask nextTask = new WorkDetailTask();
            nextTask.setMaterCode(nextAwd.getMaterNo());
            nextTask.setMaterName(nextAwd.getMaterName());
            nextTask.setApsWorkDetailId(nextAwd.getId());
            nextTask.setPlanStartDateTime(nextAwd.getPlanStartDateTime());
            nextTask.setPlanEndDateTime(nextAwd.getPlanEndDateTime());
            nextTask.setPartPath(nestPart.getPartMapUrl());
            nextTask.setOrderCode(oldTask.getOrderCode());
            nextTask.setWeight(oldTask.getWeight());
            nextTask.setNestPlateId(oldTask.getNestPlateId());
            nextTask.setTotalCount(successQuantity);
            nextTask.setFinishCount(0);
            nextTask.setFailCount(0);
            nextTask.setType(2);
            nextTask.setGroupCode(nextAwd.getGroupCode());
            nextTask.setPlmid(nextAwd.getMaterNo());
            nextTask.setPhaseCode(nextAwd.getPhaseCode());
            nextTask.setPhaseName(nextAwd.getPhaseName());
            nextTask.setPrePhaseCode(prePhaseCode);
            nextTask.setStatus(1);
            nextTask.setPartPath(nestPart.getPartMapUrl());
            nextTask.setLength(nestPart.getLength());
            nextTask.setWidth(nestPart.getWidth());
            nextTask.setPlateCode(nestPart.getPlateCode());
            nextTask.setNestId(nestPart.getNestId());
            workDetailTaskMapper.insert(nextTask);

        }
    }

    public void makeWorkDetailTask(ApsWorkDetail nextAwd, BigDecimal quantity, WorkDetailTask oldTask, String prePhaseCode) {

        if (nextAwd.getStatus() < 2) {
            nextAwd.setStatus(2);
            apsWorkDetailMapper.updateById(nextAwd);
        }

        if (quantity.intValue() > 0) {
            WorkDetailTask nextTask = new WorkDetailTask();
            nextTask.setMaterCode(nextAwd.getMaterNo());
            nextTask.setMaterName(nextAwd.getMaterName());
            nextTask.setApsWorkDetailId(nextAwd.getId());
            nextTask.setTotalCount(quantity.intValue());
            nextTask.setFinishCount(0);
            nextTask.setFailCount(0);
            nextTask.setType(2);
            nextTask.setPlanStartDateTime(nextAwd.getPlanStartDateTime());
            nextTask.setPlanEndDateTime(nextAwd.getPlanEndDateTime());
            nextTask.setGroupCode(nextAwd.getGroupCode());
            nextTask.setPlmid(nextAwd.getMaterNo());
            nextTask.setPhaseCode(nextAwd.getPhaseCode());
            nextTask.setPhaseName(nextAwd.getPhaseName());
            nextTask.setPrePhaseCode(prePhaseCode);
            nextTask.setStatus(1);
            if (ObjectUtils.isNotEmpty(oldTask)) {
                nextTask.setPartPath(oldTask.getPartPath());
                nextTask.setLength(oldTask.getLength());
                nextTask.setWidth(oldTask.getWidth());
                nextTask.setOrderCode(oldTask.getOrderCode());
                nextTask.setNestPlateId(oldTask.getNestPlateId());
                nextTask.setWeight(oldTask.getWeight());
                nextTask.setPlateCode(oldTask.getPlateCode());
                nextTask.setNestId(oldTask.getNestId());
            }

            workDetailTaskMapper.insert(nextTask);
        }
    }

    /**
     * 创建唯一件的工单任务
     *
     * @param nextAwd
     * @param prePhaseCode
     */
    public void makeUniqueCodeWorkDetailTask(ApsWorkDetail nextAwd, String prePhaseCode, Integer apsWorkDetailId, WorkDetailTask oldTask,String uniqueCode) {
        WorkDetailTask nextTask = new WorkDetailTask();
        nextTask.setMaterCode(nextAwd.getMaterNo());
        nextTask.setMaterName(nextAwd.getMaterName());
        nextTask.setApsWorkDetailId(nextAwd.getId());
        nextTask.setTotalCount(1);
        nextTask.setStatus(1);
        nextTask.setFinishCount(0);
        nextTask.setFailCount(0);
        nextTask.setType(2);
        nextTask.setGroupCode(nextAwd.getGroupCode());
        nextTask.setPlmid(nextAwd.getMaterNo());
        nextTask.setPhaseCode(nextAwd.getPhaseCode());
        nextTask.setPrePhaseCode(prePhaseCode);
        nextTask.setPhaseName(nextAwd.getPhaseName());
        nextTask.setApsWorkDetailId(nextAwd.getId());
        if (ObjectUtils.isNotEmpty(oldTask)) {
            nextTask.setPartPath(oldTask.getPartPath());
            nextTask.setLength(oldTask.getLength());
            nextTask.setWidth(oldTask.getWidth());
            nextTask.setOrderCode(oldTask.getOrderCode());
            nextTask.setNestPlateId(oldTask.getNestPlateId());
            nextTask.setWeight(oldTask.getWeight());
            nextTask.setPlateCode(oldTask.getPlateCode());
            nextTask.setNestId(oldTask.getNestId());
        }
        if(apsWorkDetailId!=null){
            // 多个人重复报工的时候，会获取同一个计划，对同一个计划进行处理
            ApsWorkDetail apsWorkDetail = apsWorkDetailMapper.selectById(apsWorkDetailId);
            if(!uniqueCode.equalsIgnoreCase(apsWorkDetail.getUniqueCode())){
                throw SyExceptionUtils.e(String.format("工件%s的资源被占用，请再次提交！", nextAwd.getMaterNo()));

            }
        }


        workDetailTaskMapper.insert(nextTask);
    }




    /**
     * 插入日子  1创建 2移动 3消费 4转换 5装盘 6卸盘
     *
     * @param operationType
     * @param nextPart
     * @param reportCount
     * @param failCount
     */
    public void createPartLog(int operationType, Part nextPart, Integer reportCount, Integer failCount, String palletCode,
                              WorkRecord workRecord, String uniCode) {
        PartLog ph = new PartLog();
        ph.setOperationType(operationType);
        ph.setPartType(2);
        ph.setConstructNo(nextPart.getConstructNo());
        ph.setPartId(nextPart.getPlmId());
        ph.setPhaseCode(nextPart.getPrePhaseCode());
        ph.setNextPhaseCode(nextPart.getPhaseCode());
        ph.setSuccessCount(reportCount);
        ph.setUniCode(uniCode);
        ph.setErrorCount(failCount);
        ph.setTotalCount(nextPart.getPartCount() + nextPart.getFailCount() - reportCount - failCount);
        ph.setAfterCount(nextPart.getPartCount() + nextPart.getFailCount());
        ph.setLoadId(palletCode);
        if(ObjectUtils.isNotEmpty(workRecord)){
            ph.setUserCode(workRecord.getWorkStaffCode());
            ph.setGroupCode(workRecord.getGroupNumber());
            ph.setStationCode(workRecord.getStationCode());
            ph.setReportId(workRecord.getId());
        }
        ph.setPrePartHistory(null);
        ph.setLoadType(1);
        partLogMapper.insert(ph);
    }
    public Part createPart(String constructNo,String plmid,Integer prePhaseSeq,String prePhaseCode, String phaseCode, String phaseName, String workChain, String nextGroup, Integer reportCount, Integer failCount) {
        // 添加下道工序的零件
        Part nextPart = partService.getPart(constructNo, plmid, phaseCode);
        if (nextPart == null) {
            nextPart = new Part();
            nextPart.setPlmId(plmid);
            nextPart.setConstructNo(constructNo);
            nextPart.setPhaseCode(phaseCode);
            nextPart.setPhaseName(phaseName);
            nextPart.setPhaseSeq(prePhaseSeq + 1);
            nextPart.setWorkGroup(nextGroup);
            nextPart.setPrePhaseCode(prePhaseCode);
            nextPart.setWorkChain(workChain);
            nextPart.setFailCount(0);
            nextPart.setPartCount(0);
            nextPart.setPartType(2);
            partMapper.insert(nextPart);
           //
        }
        partMapper.updateCount(nextPart.getId(), reportCount, failCount);
        nextPart = partService.getPart(constructNo, plmid, phaseCode);
        return nextPart;
    }




    /**
     * 1、分拣报工
     *
     * @return
     */
/*    public Part createPartInfo(ApsWorkOrder apsWorkOrder, String prePhaseCode, ApsWorkDetail nextAwd, BigDecimal success, BigDecimal failQuantity, String palletCode) {

        // 添加零件信息
        Part newPart = partMapper.lambdaQuery()
                .eq(Part::getPhaseCode, nextAwd.getPhaseCode())
                .eq(Part::getPhaseSeq, nextAwd.getPhaseSeq() - 1)
                .eq(Part::getPlmId, apsWorkOrder.getPlmId())
                .one();
        if (newPart != null) {
            newPart.setPartCount(newPart.getPartCount() + success.intValue());
            newPart.setFailCount(newPart.getFailCount() + failQuantity.intValue());
            partMapper.updateById(newPart);
        } else {
            newPart = new Part();
            newPart.setPlmId(apsWorkOrder.getPlmId());
            newPart.setPhaseSeq(nextAwd.getPhaseSeq() - 1);
            newPart.setWorkGroup(nextAwd.getGroupCode());
            newPart.setPhaseCode(nextAwd.getPhaseCode());
            newPart.setPhaseName(nextAwd.getPhaseName());
            newPart.setPrePhaseCode(prePhaseCode);
            newPart.setWorkChain(apsWorkOrder.getWorkChain());
            newPart.setFailCount(failQuantity.intValue());
            newPart.setPartCount(success.intValue());
            newPart.setPartType(2);
            partMapper.insert(newPart);
        }

        return newPart;
    }*/

    public Part createWlPart(WorkshopPartInReqVo reqVo) {
        return addPartWl(reqVo.getConstructNo(),reqVo.getPlmId(), reqVo.getQuantity());
    }

    public void putWlPallet(WorkshopPartInReqVo reqVo) {
        PartPallet partPallet = partPalletMapper.lambdaQuery()
                .eq(PartPallet::getPlmId, reqVo.getPlmId())
                .eq(PartPallet::getPhaseCode, WorkshopProp.WL_PHASE_CODE)
                .eq(PartPallet::getLoadingCode, reqVo.getPalletCode())
                .one();

        if (partPallet == null) {
            partPallet = new PartPallet();
            partPallet.setConstructNo(reqVo.getConstructNo());
            partPallet.setPartCount(reqVo.getQuantity());
            partPallet.setPlmId(reqVo.getPlmId());
            partPallet.setPhaseCode(WorkshopProp.KJ_PHASE_CODE);
            partPallet.setLoadingCode(WorkshopProp.KJ_PHASE_CODE);
            partPallet.setType(1);
            partPallet.setPrePhaseCode(null);
            partPalletMapper.insert(partPallet);
        } else {
            partPallet.setPartCount(partPallet.getPartCount() + reqVo.getQuantity());
            partPalletMapper.updateById(partPallet);
        }

    }

    /**
     * 装盘
     *
     * @param quantity
     * @param palletCode
     * @param newPart
     */
    public void putPallet(Integer quantity, String palletCode, Part newPart) {
        if(quantity < 0){
            return ;
        }

        if (org.springframework.util.StringUtils.hasText(palletCode) && !StringUtils.equals(palletCode, WorkshopProp.MES_PART_FLAGE)) {

            PartPallet nextPartPallet = partPalletMapper.lambdaQuery()
                    .eq(PartPallet::getPlmId, newPart.getPlmId())
                    .eq(PartPallet::getPhaseCode, newPart.getPhaseCode())
                    // .eq(StringUtils.isNotBlank(newPart.getPrePhaseCode()),PartPallet::getPrePhaseCode, newPart.getPrePhaseCode())
//                        .eq(newPart.getPhaseSeq()!=null,  PartPallet::getPhaseSeq, newPart.getPhaseSeq())
                    .eq(PartPallet::getLoadingCode, palletCode)
//                        .eq(PartPallet::getType, 1)
                    .one();
            if (nextPartPallet == null) {
                List<PartPallet> oldList = partPalletMapper.lambdaQuery()
                        .eq(PartPallet::getLoadingCode, palletCode)
//                            .eq(PartPallet::getType, 1)
                        .list();
                if (!CollectionUtils.isEmpty(oldList) && oldList.size() > 1) {
                    Set<String> plimids = oldList.stream().map(PartPallet::getPlmId).collect(Collectors.toSet());
                    if (plimids.size() > 1) {
                        throw SyExceptionUtils.e(String.format("装盘失败,目标托盘%s内plmid不一致", palletCode));
                    }
                    Set<String> phaseCodes = oldList.stream().map(PartPallet::getPhaseCode).collect(Collectors.toSet());
                    if (phaseCodes.size() > 1) {
                        throw SyExceptionUtils.e(String.format("装盘失败,目标托盘%s内工序不一致", palletCode));
                    }
                } else if (!CollectionUtils.isEmpty(oldList) && oldList.size() == 1 && oldList.get(0).getPartCount() > 0) {
                    String prePlimd = oldList.get(0).getPlmId();
                    String prePhase = oldList.get(0).getPhaseCode();
                    if (!StringUtils.equals(prePlimd, newPart.getPlmId())) {
                        throw SyExceptionUtils.e(String.format("装盘失败,起始托盘零件与目标托盘%s,plmid不一致", palletCode));
                        //  支持同零件混装
                    } else if (!StringUtils.equals(prePhase, newPart.getPhaseCode())) {
                        throw SyExceptionUtils.e(String.format("装盘失败,起始托盘零件的工序与目标盘%s，工序不一致", palletCode));
                    }
                }
                if (CollectionUtils.isEmpty(oldList)) {
                    nextPartPallet = new PartPallet();
                    nextPartPallet.setConstructNo(newPart.getConstructNo());
                    nextPartPallet.setPartCount(quantity);
                    nextPartPallet.setPlmId(newPart.getPlmId());
                    nextPartPallet.setPhaseCode(newPart.getPhaseCode());
                    nextPartPallet.setLoadingCode(palletCode);
                    nextPartPallet.setType(1);
                    nextPartPallet.setPartType(2);
                    nextPartPallet.setPhaseSeq(newPart.getPhaseSeq());
                    nextPartPallet.setPrePhaseCode(newPart.getPrePhaseCode());
                    partPalletMapper.insert(nextPartPallet);
                } else {
                    nextPartPallet = oldList.get(0);
                    nextPartPallet.setConstructNo(newPart.getConstructNo());
                    nextPartPallet.setPartCount(quantity);
                    nextPartPallet.setPlmId(newPart.getPlmId());
                    nextPartPallet.setPhaseCode(newPart.getPhaseCode());
                    nextPartPallet.setLoadingCode(palletCode);
                    nextPartPallet.setType(1);
                    nextPartPallet.setPartType(2);
                    nextPartPallet.setPhaseSeq(newPart.getPhaseSeq());
                    nextPartPallet.setPrePhaseCode(newPart.getPrePhaseCode());
                    partPalletMapper.updateById(nextPartPallet);
                }


            } else {
                nextPartPallet.setPartCount(nextPartPallet.getPartCount() + quantity);
                partPalletMapper.updateById(nextPartPallet);
            }
            PartLog ph = new PartLog();
            ph.setOperationType(5);
            ph.setPartType(2);
            ph.setConstructNo(newPart.getConstructNo());
            ph.setPartId(newPart.getPlmId());
            ph.setPhaseCode(newPart.getPrePhaseCode());
            ph.setNextPhaseCode(newPart.getPhaseCode());
            ph.setTotalCount(quantity);
            ph.setSuccessCount(quantity);
            ph.setErrorCount(0);
            ph.setUniCode(null);
            ph.setPrePartHistory(null);
            ph.setLoadType(1);
            ph.setLoadId(nextPartPallet.getLoadingCode());
            int sum = partPalletMapper.lambdaQuery()
                    .eq(PartPallet::getPlmId, newPart.getPlmId())
                    .eq(org.springframework.util.StringUtils.hasText(newPart.getPhaseCode()), PartPallet::getPhaseCode, newPart.getPhaseCode())
                    .eq(org.springframework.util.StringUtils.hasText(newPart.getPrePhaseCode()), PartPallet::getPrePhaseCode, newPart.getPrePhaseCode())
                    .list()
                    .stream()
                    .mapToInt(PartPallet::getPartCount)
                    .sum();
            ph.setAfterCount(sum + quantity);
            partLogMapper.insert(ph);
        }


    }

    /**
     *  支持多种零件混放

     */
    public void putMultiplePallet(int quantity, String palletCode, Part newPart) {
        if(quantity>0){
            if (org.springframework.util.StringUtils.hasText(palletCode) && !StringUtils.equals(palletCode,WorkshopProp.MES_PART_FLAGE)) {
                PartPallet nextPartPallet = partPalletMapper.lambdaQuery()
                        .eq(PartPallet::getPlmId, newPart.getPlmId())
                        .eq(PartPallet::getPhaseCode, newPart.getPhaseCode())
                        .eq(PartPallet::getLoadingCode, palletCode)
                        .eq(PartPallet::getType, 1)
                        .one();
                if (nextPartPallet == null) {
                    nextPartPallet = new PartPallet();
                    nextPartPallet.setPartCount(quantity);
                    nextPartPallet.setPlmId(newPart.getPlmId());
                    nextPartPallet.setConstructNo(newPart.getConstructNo());
                    nextPartPallet.setPhaseCode(newPart.getPhaseCode());
                    nextPartPallet.setLoadingCode(palletCode);
                    nextPartPallet.setType(1);
                    nextPartPallet.setPartType(2);
                    nextPartPallet.setPhaseSeq(newPart.getPhaseSeq());
                    nextPartPallet.setPrePhaseCode(newPart.getPrePhaseCode());
                    partPalletMapper.insert(nextPartPallet);
                } else {
                    nextPartPallet.setPartCount(nextPartPallet.getPartCount() + quantity);
                    partPalletMapper.updateById(nextPartPallet);
                }
                PartLog ph = new PartLog();
                ph.setOperationType(5);
                ph.setPartType(2);
                ph.setConstructNo(newPart.getConstructNo());
                ph.setPartId(newPart.getPlmId());
                ph.setPhaseCode(newPart.getPrePhaseCode());
                ph.setNextPhaseCode(newPart.getPhaseCode());
                ph.setTotalCount(quantity);
                ph.setSuccessCount(quantity);
                ph.setErrorCount(0);
                ph.setUniCode(null);
                ph.setPrePartHistory(null);
                ph.setLoadType(1);
                ph.setLoadId(nextPartPallet.getLoadingCode());
                int sum = partPalletMapper.lambdaQuery()
                        .eq(PartPallet::getPlmId, newPart.getPlmId())
                        .eq(org.springframework.util.StringUtils.hasText(newPart.getPhaseCode()), PartPallet::getPhaseCode,newPart.getPhaseCode())
                        .eq(org.springframework.util.StringUtils.hasText(newPart.getPrePhaseCode()), PartPallet::getPrePhaseCode, newPart.getPrePhaseCode())
                        .list()
                        .stream()
                        .mapToInt(PartPallet::getPartCount)
                        .sum();
                ph.setAfterCount(sum+quantity);
                partLogMapper.insert(ph);
            }

        }

    }
    /**
     * 组件装配
     *
     * @param partNew
     * @param station
     * @param uniqueCode
     */
    public void putUniqueCode(Part partNew, String station, String uniqueCode) {
        PartPallet partPalletNew=null;
        List<PartPallet> list = partPalletMapper.lambdaQuery().eq(PartPallet::getUniqueCode, uniqueCode).list();
        // 解决唯一号重复的问题
        if(!CollectionUtils.isEmpty(list)){
            for (PartPallet partPallet : list){
                if(partNew.getPlmId().equalsIgnoreCase(partPallet.getPlmId())){
                    partPalletNew=partPallet;
                }else{
                    partPalletMapper.deleteReal(partPallet.getId());
                }
            }
        }
// 添加零件信息
      /*  PartPallet partPalletNew = partPalletMapper.lambdaQuery()
                .eq(PartPallet::getPlmId, partNew.getPlmId())
                .eq(PartPallet::getUniqueCode, uniqueCode)
                .one();*/
        QueryWrapper<NoreportErpConfig> query = new QueryWrapper<>();
        query.eq("deleted", 0);
        query.eq("phase",partNew.getPlmId());
        query.like("plmid", partNew.getPrePhaseCode());
        List<NoreportErpConfig> noreportErpConfigs = noreportErpConfigMapper.selectList(query);

        if (ObjectUtils.isEmpty(partPalletNew)) {
            partPalletNew = new PartPallet();
            partPalletNew.setPartCount(1);
            partPalletNew.setPlmId(partNew.getPlmId());
            partPalletNew.setConstructNo(partNew.getConstructNo());
           
             if(!CollectionUtils.isEmpty(noreportErpConfigs)){
                 partPalletNew.setPhaseCode(WorkshopProp.RK_PHASE_CODE);
             }else if(StringUtils.isNotBlank(partNew.getPrePhaseCode())&&StringUtils.equalsIgnoreCase(partNew.getPrePhaseCode(),WorkshopProp.PT_PHASE_CODE)){
                partPalletNew.setPhaseCode(WorkshopProp.RK_PHASE_CODE);
            }else{
                //  组件如果没有父级  则定义为入库
                ApsWorkOrder one = apsWorkOrderMapper.lambdaQuery().eq(ApsWorkOrder::getPlmId, partNew.getPlmId()).last(" limit 1 ").one();
                if(ObjectUtils.isNotEmpty( one)&&one.getPid()==null){
                    partPalletNew.setPhaseCode(WorkshopProp.RK_PHASE_CODE);
                }else{
                    partPalletNew.setPhaseCode(partNew.getPhaseCode());
                }

            }
            partPalletNew.setPhaseSeq(partNew.getPhaseSeq());
            partPalletNew.setStationCode(station);
            partPalletNew.setType(3);
            partPalletNew.setPartType(2);
            partPalletNew.setPrePhaseCode(partNew.getPrePhaseCode());

            if (partPalletNew.getPlmId().equalsIgnoreCase("P1_170")) {
                partPalletNew.setUniqueCode(uniqueCode);
            } else if (!uniqueCode.isEmpty()) {
                partPalletNew.setUniqueCode(uniqueCode);
            }
            partPalletMapper.insert(partPalletNew);
        } else {
            if(!CollectionUtils.isEmpty(noreportErpConfigs)) {
                partPalletNew.setPhaseCode(WorkshopProp.RK_PHASE_CODE);
            }else if(StringUtils.isNotBlank(partNew.getPrePhaseCode())&&StringUtils.equalsIgnoreCase(partNew.getPrePhaseCode(),WorkshopProp.PT_PHASE_CODE)){
                partPalletNew.setPhaseCode(WorkshopProp.RK_PHASE_CODE);
            }else{
                //  组件如果没有父级  则定义为入库
                ApsWorkOrder one = apsWorkOrderMapper.lambdaQuery().eq(ApsWorkOrder::getPlmId, partNew.getPlmId()).last(" limit 1 ").one();
                if(ObjectUtils.isNotEmpty( one)&&one.getPid()==null){
                    partPalletNew.setPhaseCode(WorkshopProp.RK_PHASE_CODE);
                }else{
                    partPalletNew.setPhaseCode(partNew.getPhaseCode());
                }
            }
            partPalletNew.setPhaseSeq(partNew.getPhaseSeq());
//            partPalletNew.setStationCode(station);
            partPalletNew.setPrePhaseCode(partNew.getPrePhaseCode());
            partPalletMapper.updateById(partPalletNew);
        }
        PartLog ph = new PartLog();
        ph.setOperationType(5);
        ph.setPartType(2);
        ph.setConstructNo(partNew.getConstructNo());
        ph.setPartId(partNew.getPlmId());
        ph.setPhaseCode(partNew.getPrePhaseCode());
        ph.setNextPhaseCode(partNew.getPhaseCode());
        ph.setTotalCount(1);
        ph.setSuccessCount(1);
        ph.setErrorCount(0);
        ph.setStationCode(station);
        ph.setUniCode(partPalletNew.getUniqueCode());
        ph.setPrePartHistory(null);
        ph.setLoadType(1);
        ph.setLoadId(station);
        partLogMapper.insert(ph);

    }

    /**
     * 将零件散落到工位
     *
     * @param partPallet
     * @param myCode
     */
    public void putPartToStation(PartPallet partPallet, String myCode) {
        PartLog ph = new PartLog();
        ph.setOperationType(2);
        ph.setPartType(2);
        ph.setPartId(partPallet.getPlmId());
        ph.setConstructNo(partPallet.getConstructNo());
        ph.setPhaseCode(partPallet.getPrePhaseCode());
        ph.setNextPhaseCode(partPallet.getPhaseCode());
        ph.setTotalCount(partPallet.getPartCount());
        ph.setLoadId(partPallet.getLoadingCode() + ">" + myCode);
        ph.setSuccessCount(partPallet.getPartCount());
        ph.setErrorCount(0);
        ph.setLoadType(1);
        partLogMapper.insert(ph);
        PartPallet nextPartPallet = partPalletMapper.lambdaQuery()
                .eq(PartPallet::getPlmId, partPallet.getPlmId())
                .eq(PartPallet::getPhaseCode, partPallet.getPhaseCode())
                .eq(PartPallet::getPositionCode, myCode)
                .eq(PartPallet::getType, 3)
                .one();
        if (nextPartPallet == null) {
            nextPartPallet = new PartPallet();
            nextPartPallet.setConstructNo(partPallet.getConstructNo());
            nextPartPallet.setPartCount(partPallet.getPartCount());
            nextPartPallet.setPlmId(partPallet.getPlmId());
            nextPartPallet.setPhaseCode(partPallet.getPhaseCode());
            nextPartPallet.setLoadingCode(null);
            nextPartPallet.setPositionCode(myCode);
            nextPartPallet.setType(3);
            nextPartPallet.setPrePhaseCode(partPallet.getPrePhaseCode());
            partPalletMapper.insert(nextPartPallet);
        } else {
            nextPartPallet.setPartCount(nextPartPallet.getPartCount() + partPallet.getPartCount());
            nextPartPallet.setType(3);
            partPalletMapper.updateById(nextPartPallet);
        }
        partPalletMapper.deleteReal(partPallet.getId());
    }

    /**
     * 从托盘中扣减零件
     *
     * @param partPallet
     * @param partCount
     * @param send
     */
    public void reducePartFromPallet(PartPallet partPallet, int partCount, boolean send) {
        PartLog ph = new PartLog();
        ph.setOperationType(6);

        ph.setPartType(2);
        ph.setPartId(partPallet.getPlmId());
        ph.setPhaseCode(partPallet.getPrePhaseCode());
        ph.setNextPhaseCode(partPallet.getPhaseCode());
        ph.setTotalCount(partPallet.getPartCount());
        ph.setLoadId(partPallet.getLoadingCode());
        ph.setConstructNo(partPallet.getConstructNo());
        ph.setSuccessCount(partCount);
        ph.setErrorCount(0);
        ph.setLoadType(1);
        int sum = partPalletMapper.lambdaQuery()
                .eq(PartPallet::getPlmId, partPallet.getPlmId())
                .eq(org.springframework.util.StringUtils.hasText(partPallet.getPhaseCode()), PartPallet::getPhaseCode,partPallet.getPhaseCode())
                .eq(org.springframework.util.StringUtils.hasText(partPallet.getPrePhaseCode()), PartPallet::getPrePhaseCode, partPallet.getPrePhaseCode())
                .list()
                .stream()
                .mapToInt(PartPallet::getPartCount)
                .sum();
        ph.setAfterCount(sum - partCount);
        partLogMapper.insert(ph);
        // 工位\拖盘零件扣减

        partPallet.setPartCount(partPallet.getPartCount() - partCount);

        if (partPallet.getPartCount() < 0) {
            throw SyExceptionUtils.e("托盘[{}]数量不足,目前已超数量：{}", partPallet.getLoadingCode(), Math.abs(partPallet.getPartCount()));
        }
        if (partPallet.getPartCount() == 0) {
            partPalletMapper.deleteReal(partPallet.getId());
            if(send){
                wmsApiClient.clearPallet(Lists.newArrayList(partPallet.getLoadingCode()));
            }
        } else {
            partPalletMapper.updateById(partPallet);
        }

    }

    public int reportClearCount(String partId, String nextPhaseCode) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime oneHourAgo = now.minusHours(1);
        List<PartLog> list = partLogMapper.lambdaQuery()
                .eq(PartLog::getPartId, partId)
                .eq(PartLog::getNextPhaseCode, nextPhaseCode)
                .eq(PartLog::getOperationType, 6)
                .eq(PartLog::getPartType, 2)
                .gt(PartLog::getCreateDateTime, oneHourAgo)
                .list();
        int sum = list.stream().mapToInt(PartLog::getSuccessCount).sum();

        return sum;
    }

    /**
     * 页面配盘报工、暂时废弃
     * 向托盘中添加零件
     *
     * @param newPP
     * @param partCount
     */
/*    public void putPartToPallet(PartPallet newPP, int partCount) {
        PartLog ph = new PartLog();
        ph.setOperationType(5);
        ph.setPartType(2);
        ph.setPartId(newPP.getPlmId());
        ph.setPhaseCode(newPP.getPrePhaseCode());
        ph.setNextPhaseCode(newPP.getPhaseCode());
        ph.setTotalCount(newPP.getPartCount());
        ph.setLoadId(newPP.getLoadingCode());
        ph.setSuccessCount(partCount);
        ph.setErrorCount(0);
        ph.setLoadType(1);
        partLogMapper.insert(ph);
        newPP.setPartCount(newPP.getPartCount() + partCount);
        partPalletMapper.updateById(newPP);
    }*/

    /**
     * 消费零件
     *
     * @param part
     */
    public void consumePart(Part part, int partCount, String groupNumber,String staffCode,Integer reportId,String parentPlmid) {
        PartLog ph = new PartLog();
        ph.setOperationType(3);
        ph.setPartType(2);
        ph.setPartId(part.getPlmId());
        ph.setPhaseCode(part.getPrePhaseCode());
        ph.setNextPhaseCode(part.getPhaseCode());
        ph.setGroupCode(groupNumber);
        ph.setUserCode(staffCode);
        ph.setReportId(reportId);
        ph.setConstructNo(part.getConstructNo());
        ph.setTotalCount(part.getPartCount());
        ph.setSuccessCount(partCount);
        ph.setAfterCount(part.getPartCount() - partCount);
        ph.setErrorCount(0);
        ph.setLoadType(1);
        ph.setParentPlmid(parentPlmid);
        partLogMapper.insert(ph);

        if(part.getPartCount()>=partCount){
            partMapper.consumePart(part.getId(),partCount);

        }else{
            int left=partCount-part.getPartCount();
             partMapper.consumePart(part.getId(),part.getPartCount());
            int allCount = partMapper.lambdaQuery().eq(Part::getPlmId,  part.getPlmId()).eq(Part::getPhaseCode, part.getPhaseCode()).gt(Part::getPartCount, 0).list().stream().mapToInt(Part::getPartCount).sum();
            if(allCount>=left){
               List<Part> partList = partMapper.lambdaQuery().ne(Part::getId, part.getId()).eq(Part::getPlmId,  part.getPlmId()).eq(Part::getPhaseCode, part.getPhaseCode()).list();
              for (Part other : partList){
                  if(left==0){
                      break;
                  }
                 if(other.getPartCount()>=left){
                     partMapper.consumePart(other.getId(),left);
                     left=0;
                 }else{
                     left=left-other.getPartCount();
                     partMapper.consumePart(other.getId(),other.getPartCount());
                 }
              }
            }else{
                List<Part> partFailList = partMapper.lambdaQuery().eq(Part::getPlmId,  part.getPlmId()).gt(Part::getFailCount, 0).list();
                int failCount = partFailList.stream().mapToInt(Part::getFailCount).sum();
                throw SyExceptionUtils.e("零件{}工序{}数量不足,目前已超数量：{}，异常零件数量{}", part.getPlmId(),part.getPhaseCode(),Math.abs(left-allCount),failCount);
            }

        }


 /*
 前期先不控制托盘的零件
 int palletSum =  partPalletMapper.lambdaQuery().eq(PartPallet::getPlmId, part.getPlmId())
                .eq(PartPallet::getPrePhaseCode, part.getPrePhaseCode()).isNotNull(PartPallet::getLoadingCode).isNull(PartPallet::getUniqueCode).list().stream().mapToInt(PartPallet::getPartCount).sum();
        if(part.getPartCount()<palletSum){
            throw SyExceptionUtils.e("零件数量不足,零件的装配数量大于散落的数量：{}", part.getPlmId());
        }*/



    }

    public Part addPartWl(String constructNo,String materCode, Integer totalCount) {

        Part part = partService.getPart(constructNo, materCode, WorkshopProp.KJ_PHASE_CODE);
        if (part == null) {
            part = new Part();
            part.setPlmId(materCode);
            part.setConstructNo(constructNo);
            part.setWorkChain(WorkshopProp.WL_PHASE_CODE);
            part.setPhaseCode(WorkshopProp.KJ_PHASE_CODE);
            part.setPhaseName(WorkshopProp.KJ_PHASE_NAME);
            part.setPrePhaseCode(WorkshopProp.WL_PHASE_CODE);
            part.setFailCount(0);
            part.setPartCount(totalCount);
            part.setPartType(3);
            partMapper.insert(part);
        } else {
            part.setPartCount(part.getPartCount() + totalCount);
            partMapper.updateById(part);
        }
        //添加零件日志
        PartLog partLog = new PartLog();
        partLog.setOperationType(1);
        partLog.setPartType(3);
        partLog.setConstructNo(constructNo);
        partLog.setPartId(materCode);
        partLog.setPhaseCode(WL_PHASE_CODE);
        partLog.setNextPhaseCode(WorkshopProp.KJ_PHASE_CODE);
        partLog.setReportId(null);
        partLog.setTotalCount(part.getPartCount()-totalCount);
        partLog.setSuccessCount(totalCount);
        partLog.setErrorCount(0);
        partLog.setAfterCount(part.getPartCount());
        partLogMapper.insert(partLog);
        return part;

    }

    /**
     *创建库检报工记录
     */
    public void makePartKjReport(String constructNo,String groupNumber,String stationCode,String plmid,String palletNumber, int complateCount, int leftFailReport, String staffCode,int awdID) {
        OrderBom orderBom = orderBomMapper.lambdaQuery().eq(OrderBom::getPlmId,plmid).last(" limit 1 ").one();
        if (orderBom != null) {
            OrderBom orderBomP = orderBomMapper.lambdaQuery().eq(OrderBom::getId, orderBom.getPid()).last(" limit 1 ").one();
            if (orderBomP != null && NameEqualsUtils.equals(orderBomP.getMaterName())) {
               return;
            }
        }
        if(complateCount-leftFailReport<1){
            return;
        }
        WorkRecord workRecordPart = new WorkRecord();
        workRecordPart.setType(2);
        workRecordPart.setErpState(0);
        workRecordPart.setWorkType(2);
        workRecordPart.setPlmid(plmid);
        workRecordPart.setConstructNo(constructNo);
        workRecordPart.setWorkDate(LocalDate.now());
        workRecordPart.setPhaseCode(WorkshopProp.KJ_PHASE_CODE);
        workRecordPart.setStorageNumber(null);
        workRecordPart.setPalletNumber(palletNumber);
        workRecordPart.setGroupNumber(groupNumber);
        workRecordPart.setStationCode(stationCode);
        workRecordPart.setWorkStaffCode(staffCode);
        workRecordPart.setTotalCount(complateCount);
        workRecordPart.setSuccessCount(complateCount-leftFailReport);
        workRecordPart.setFailCount(leftFailReport);
        workRecordPart.setApsWorkDetailId(awdID);
        workRecordPart.setStartTime(LocalDateTime.now().minusMinutes(2));
        workRecordPart.setWorkTime(LocalDateTime.now());
        workRecordMapper.insert(workRecordPart);
    }

    /**
     *
     * @param groupNumber
     * @param stationCode
     * @param type   1钢板 2零件
     * @param workType   操作类型，1开工 2报工
     * @param palletNumber
     * @param complateCount
     * @param staffCode
     * @param awdID
     */
    public void startPartReport(String groupNumber, String stationCode, int type, int workType,
                                String plmid, String phaseCode, String palletNumber,
                                Integer complateCount, String staffCode, Integer taskId, Integer awdID) {
        WorkRecord workRecordPart = new WorkRecord();
        workRecordPart.setType(type);
        workRecordPart.setErpState(0);
        workRecordPart.setWorkType(1);
        workRecordPart.setPlmid(plmid);
        workRecordPart.setFailCount(0);
        workRecordPart.setSuccessCount(0);
        workRecordPart.setPhaseCode(phaseCode);
        workRecordPart.setStorageNumber(null);
        workRecordPart.setWorkDate(LocalDate.now());
        workRecordPart.setPalletNumber(palletNumber);
        workRecordPart.setGroupNumber(groupNumber);
        workRecordPart.setStationCode(stationCode);
        workRecordPart.setWorkStaffCode(staffCode);
        workRecordPart.setTotalCount(complateCount);
        workRecordPart.setOperationId(taskId);
        workRecordPart.setWorkTime(LocalDateTime.now());
        workRecordPart.setApsWorkDetailId(awdID);
        workRecordPart.setStartTime(LocalDateTime.now());
        workRecordMapper.insert(workRecordPart);
    }

    /**
     *
     * @param groupNumber
     * @param stationCode
     * @param type   1钢板 2零件
     * @param workType   操作类型，1开工 2报工
     * @param plmid
     * @param phaseCode
     * @param palletNumber
     * @param complateCount
     * @param staffCode
     * @param taskId
     * @param awdID
     * @return
     */
    public WorkRecord complatePartReport(String constructNo,String groupNumber,String stationCode,int type,int workType,String plmid,
                                         String phaseCode,String palletNumber, int complateCount,
                                         int failCount, String staffCode,Integer taskId,Integer awdID,Integer startId,
                                         LocalDateTime startTime,String plateCode) {
        //钢板报工记录
        WorkRecord workRecord = new WorkRecord();
        workRecord.setPlmid(plmid);
        workRecord.setPhaseCode(phaseCode);
        workRecord.setConstructNo(constructNo);
        workRecord.setWorkType(2);
        workRecord.setType(type);
        workRecord.setErpState(0);
        workRecord.setTotalCount(complateCount);
        workRecord.setFailCount(failCount);
        workRecord.setSuccessCount(complateCount - failCount);
        workRecord.setWorkStaffCode(staffCode);
        workRecord.setStationCode(stationCode);
        workRecord.setPalletNumber(palletNumber);
        workRecord.setAttr(plateCode);
        workRecord.setGroupNumber(groupNumber);
        workRecord.setOperationId(taskId);
        workRecord.setApsWorkDetailId(awdID);
        try {
            Map<String, String> erpWorkOrderCode = workRecordMapper.getErpWorkOrderCode(plmid, phaseCode);
            if (!CollectionUtils.isEmpty(erpWorkOrderCode)) {
                workRecord.setErpCode(erpWorkOrderCode.get("erpCode"));
                workRecord.setWorkOrderCode(erpWorkOrderCode.get("workOrderCode"));
                int index = 0;
                String phase = phaseCode;
                if (phaseCode.indexOf("0") > 0) {
                    phase = phaseCode.substring(0, phaseCode.indexOf("0"));
                    index = Integer.parseInt(phaseCode.substring(phaseCode.indexOf("0"))) - 1;
                }
                List<Map<String, Object>> erpWorkGroups = workRecordMapper.getErpWorkGroup(erpWorkOrderCode.get("workOrderCode"), erpWorkOrderCode.get("erpCode"), phase);
                if (!CollectionUtils.isEmpty(erpWorkGroups)) {
                    Map<String, Object> erpWorkGroup = erpWorkGroups.get(index);
                    if (erpWorkGroup != null) {
                        workRecord.setErpPhaseCode(erpWorkGroup.get("erpOp").toString());
                        workRecord.setErpGroupNumber(erpWorkGroup.get("erpOpCode").toString());
                    }
                }
            }
        } catch (NumberFormatException e) {
        }

        workRecord.setWorkDate(LocalDate.now());
        workRecord.setWorkTime(LocalDateTime.now());
        workRecord.setStartTime(LocalDateTime.now());
        if (startId != null) {
            workRecord.setStartId(startId);
            workRecord.setStartTime(startTime);
        } else {
            workRecord.setStartTime(LocalDateTime.now().minusMinutes(2));
        }
        workRecordMapper.insert(workRecord);
        return workRecord;
    }

    public ApsWorkDetail updateDetailState(int detailId) {
        ApsWorkDetail awd=apsWorkDetailMapper.selectById(detailId);
        if(ObjectUtils.isEmpty(awd.getActualStartDateTime())){
            awd.setActualStartDateTime(LocalDateTime.now());
        }
        if (awd.getStatus()<3) {
            awd.setStatus(3);
        }
        if(awd.getFinishCount().compareTo(awd.getTotalCount())>=0){
            awd.setStatus(4);
        }
        apsWorkDetailMapper.updateById(awd);
        return awd;
    }

    public void updateOrderState(ApsWorkOrder apsWorkOrder,  ApsOrder apsOrder ,int reportCount) {
      if(ObjectUtils.isNotEmpty(apsWorkOrder)&& StringUtils.isNotBlank(apsWorkOrder.getWorkChain())&& apsWorkOrder.getWorkChain().contains("-")){
          String str = apsWorkOrder.getWorkChain();
          String[] parts = str.split("-");  // 按 "-" 分割字符串
          String lastPart = parts[parts.length - 1];  // 获取最后一个部分
          int sum = apsWorkDetailMapper.lambdaQuery().eq(ApsWorkDetail::getApsWorkOrderId, apsWorkOrder.getId())
                  .eq(ApsWorkDetail::getPhaseCode, lastPart).list().stream().mapToInt(t->t.getFinishCount().intValue()).sum();
          apsWorkOrderMapper.lambdaUpdate().eq(ApsWorkOrder::getId, apsWorkOrder.getId())
                  .set(ApsWorkOrder::getActualEndDateTime, LocalDateTime.now())
                  .set(apsWorkOrder.getOrderCount().intValue() == sum,ApsWorkOrder::getStatus, 4)
                  .set(ApsWorkOrder::getFinishCount, sum)
                  .update();

      }else{
          apsWorkOrderMapper.lambdaUpdate().eq(ApsWorkOrder::getId, apsWorkOrder.getId())
                  .set(ApsWorkOrder::getActualEndDateTime, LocalDateTime.now())
                  .setSql("finish_count=finish_count+"+reportCount).update();
          if (apsWorkOrder.getOrderCount().intValue() <= apsWorkOrder.getFinishCount().intValue()+ reportCount) {
              apsWorkOrderMapper.lambdaUpdate().eq(ApsWorkOrder::getId, apsWorkOrder.getId())
                      .set(ApsWorkOrder::getStatus, 4).update();
          }
      }




        if (apsWorkOrder.getPid() == null) {
            if(ObjectUtils.isEmpty(apsOrder)){
                 apsOrder = apsOrderMapper.selectById(apsWorkOrder.getApsOrderId());
            }
            apsOrderMapper.lambdaUpdate().eq(ApsOrder::getId, apsOrder.getId())
                    .setSql("finish_qty=finish_qty+"+reportCount).update();

            if (apsOrder.getOrderQty() <= apsOrder.getFinishQty() + reportCount) {
                apsOrderMapper.lambdaUpdate().eq(ApsOrder::getId,apsOrder.getId()).set(ApsOrder::getOrderStatus,9)
                        .set(ApsOrder::getActualFinishTime,LocalDateTime.now()).update();
            }
            // 再判断是否所有的子订单都完成，如果
            Integer count = apsOrderMapper.lambdaQuery()
                    .eq(ApsOrder::getOrderId, apsOrder.getOrderId())
                    .ne(ApsOrder::getOrderStatus, 9)
                    .count();
            orderMapper.lambdaUpdate().eq(Order::getId, apsOrder.getOrderId())
                    .set(count==0,Order::getOrderStatus,9)
                    .set(count==0,Order::getActualEndDateTime,LocalDateTime.now())
                    .setSql("finish_qty=finish_qty+"+reportCount)
                    .update();

        }else{
            ApsWorkDetail partDetail = apsWorkDetailMapper.lambdaQuery().eq(ApsWorkDetail::getApsWorkOrderId, apsWorkOrder.getPid()).last("LIMIT 1").one();
            if(ObjectUtils.isNotEmpty(partDetail)&&StringUtils.equals(partDetail.getPhaseCode(), "WW")&&StringUtils.equals(partDetail.getMaterName(), "侧板")){
                //  获取最小的完成数量
                ApsWorkOrder entity = apsWorkOrderMapper.lambdaQuery().eq(ApsWorkOrder::getPid, apsWorkOrder.getPid()).orderByAsc(ApsWorkOrder::getFinishCount).last("LIMIT 1 ").one();
                apsWorkOrderMapper.lambdaUpdate().eq(ApsWorkOrder::getId, apsWorkOrder.getPid())
                        .set(ApsWorkOrder::getActualEndDateTime, LocalDateTime.now())
                        .set(ApsWorkOrder::getFinishCount,entity.getFinishCount())
                         .update();
                ApsWorkOrder parent = apsWorkOrderMapper.lambdaQuery().eq(ApsWorkOrder::getId, apsWorkOrder.getPid()).one();
                if (parent.getStatus()<4&&parent.getOrderCount().intValue() <= parent.getFinishCount().intValue()) {
                    apsWorkOrderMapper.lambdaUpdate().eq(ApsWorkOrder::getId, apsWorkOrder.getId())
                            .set(ApsWorkOrder::getStatus, 4).update();
                }
                if(ObjectUtils.isEmpty(apsOrder)){
                    apsOrder = apsOrderMapper.selectById(entity.getApsOrderId());
                }
                apsOrder.setFinishQty(entity.getFinishCount().intValue());
                if(Objects.equals(apsOrder.getFinishQty(), apsOrder.getOrderQty())){
                    apsOrder.setOrderStatus(9);
                    apsOrder.setActualFinishTime(LocalDateTime.now());
                    apsOrderMapper.updateById(apsOrder);
                }
                // 再判断是否所有的子订单都完成，如果
                Integer count = apsOrderMapper.lambdaQuery()
                        .eq(ApsOrder::getOrderId, apsOrder.getOrderId())
                        .ne(ApsOrder::getOrderStatus, 9)
                        .count();
                Integer finshCount = apsOrderMapper.lambdaQuery()
                        .select(ApsOrder::getFinishQty)
                        .eq(ApsOrder::getOrderId, apsOrder.getOrderId())
                        .list()
                        .stream()
                        .mapToInt(ApsOrder::getFinishQty)
                        .sum();
                orderMapper.lambdaUpdate().eq(Order::getId, apsOrder.getOrderId())
                        .set(count==0,Order::getOrderStatus,9)
                        .set(count==0,Order::getActualEndDateTime,LocalDateTime.now())
                        .set(Order::getFinishQty,finshCount)
                        .update();


            }

        }
    }

    public void kaiConsumerPart(List<Part> part, String constructNo, int reportCount, String groupNumber, String workStaffCode, Integer workRecordId, String materNo) {

        Integer myConsCount = part.stream().filter(e->e.getConstructNo().equals(constructNo)).map(Part::getPartCount).reduce(0, Integer::sum);
        if (reportCount > myConsCount) {
            // 需要借件
            // 先排序，相同号的排最前面，否则为最后面
            // 从最前面开始扣，如果施工号不同，则为借件
            List<Part> collect = part.stream()
                    .sorted((e1, e2) -> {
                        if (e1.getConstructNo().equals(e2.getConstructNo())) {
                            return 1;
                        }
                        return -1;
                    })
                    .collect(Collectors.toList());

            int shengyu = reportCount;
            for (Part part1 : collect) {
                if (part1.getPartCount() == 0) {
                    continue;
                }

                int consumeCount = part1.getPartCount();
                if (part1.getPartCount() > shengyu) {
                    consumeCount = shengyu;
//                        partUtilService.consumePart(part1, shengyu, workRecord.getGroupNumber(), workRecord.getWorkStaffCode(), workRecord.getId(), apsWorkDetail.getMaterNo());
//                        shengyu = 0;
                }
                consumePart(part1, consumeCount, groupNumber, workStaffCode, workRecordId, materNo);

                shengyu -= consumeCount;

                if(constructNo.equals(part1.getConstructNo())){
                    if (shengyu == 0) {
                        break;
                    } else {
                        continue;
                    }
                }



                PoolPart jiePoolPart = poolPartMapper.lambdaQuery()
                        .eq(PoolPart::getMyCode, constructNo)
                        .eq(PoolPart::getTargetCode, part1.getConstructNo())
                        .eq(PoolPart::getPlmId, part1.getPlmId())
                        .eq(PoolPart::getPhaseCode, part1.getPhaseCode())
                        .one();
                if (jiePoolPart == null) {
                    jiePoolPart = new PoolPart();
                    jiePoolPart.setMyCode(constructNo);
                    jiePoolPart.setTargetCode(part1.getConstructNo());
                    jiePoolPart.setPlmId(part1.getPlmId());
                    jiePoolPart.setInTotal(consumeCount);
                    jiePoolPart.setPhaseCode(part1.getPhaseCode());
                    jiePoolPart.setOutTotal(0);
                    jiePoolPart.setVersion(1);
                    poolPartMapper.insert(jiePoolPart);


                } else {
                    jiePoolPart.setInTotal(jiePoolPart.getInTotal() + consumeCount);
                    int i = poolPartMapper.updateById(jiePoolPart);
                    if(i <= 0){
                        throw SyExceptionUtils.e("请重新报工!");
                    }
                }

                PoolLog pl = new PoolLog();
                pl.setPoolPartId(jiePoolPart.getId());
                pl.setMyCode(jiePoolPart.getMyCode());
                pl.setTargetCode(jiePoolPart.getTargetCode());
                pl.setPlmId(jiePoolPart.getPlmId());
                pl.setPhaseCode(jiePoolPart.getPhaseCode());
                pl.setType(1);
                pl.setTotal(consumeCount);
                poolLogMapper.insert(pl);

                if (shengyu == 0) {
                    break;
                }

            }

        } else {
            // 不需要借件
            Optional<Part> first = part.stream().filter(e -> e.getConstructNo().equals(constructNo)).findFirst();
            consumePart(first.get(), reportCount, groupNumber, workStaffCode, workRecordId, materNo);

        }

    }

}
